#include "rpc/net/event_pooler.h"
#include "include/event_manager.h"

DEFINE_int32(worker_cnt, 4, " pool worker number");

namespace rpc {

EventManagerPool::EventManagerPool(EventManager* base_poll)
    : index_(0), base_mgr_(base_poll) {
}

EventManagerPool::~EventManagerPool() {
  ScopedMutex l(&mutex_);
  STLClear(&ev_mgrs_);
}

EventManager* EventManagerPool::getPoller() {
  ScopedMutex l(&mutex_);
  if (ev_mgrs_.empty() || index_ == ev_mgrs_.size()) {
    index_ = 0;
    return base_mgr_;
  }

  return ev_mgrs_[index_++];
}

bool EventManagerPool::Start() {
  ScopedMutex l(&mutex_);

  for (size_t i = 0; i < FLAGS_worker_cnt; ++i) {
    EventManager* p = CreatePoller();
    if (p == NULL || !p->Init()) {
      STLClear(&ev_mgrs_);
      return false;
    }
    p->LoopInAnothreadThread();

    ev_mgrs_.push_back(p);
  }

  return true;
}

}
